<template>
  <div class="page-container">
    <div class="chat-container">
      <div class="message-list" ref="messageList">
        <div v-for="(message, index) in messages" :key="index" :class="['message', message.role]">
          <div class="message-content" v-html="renderMessage(message.content)"></div>
        </div>
      </div>

      <div class="input-area">
        <form @submit.prevent="sendMessage">
          <input
            style="width: 1000px"
            v-model="userInput"
            type="text"
            placeholder="请输入您的问题..."
            :disabled="isLoading"
          />
          <button type="submit" :disabled="isLoading || !userInput.trim()">
            {{ isLoading ? '等待回复...' : '发送' }}
          </button>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css' // 选择你喜欢的代码高亮主题
import { env } from '@/utils'


interface Message {
  role: 'user' | 'assistant'
  content: string
}

// 配置 marked
// marked.setOptions({
//   highlight: function (code: string, lang: string) {
//     if (lang && hljs.getLanguage(lang)) {
//       try {
//         return hljs.highlight(code, { language: lang }).value
//       } catch (__) {}
//     }
//     return hljs.highlightAuto(code).value
//   },
//   breaks: true, // 支持 GitHub 风格的换行
//   gfm: true, // 支持 GitHub 风格的 Markdown
// })

const messages = ref<Message[]>([])
const userInput = ref('')
const isLoading = ref(false)
const messageList = ref<HTMLElement | null>(null)

// 安全的渲染 markdown
const renderMessage = (content: string) => {
  try {
    return marked(content)
  } catch (e) {
    console.error('Markdown 渲染错误:', e)
    return content
  }
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messageList.value) {
    messageList.value.scrollTop = messageList.value.scrollHeight
  }
}

const sendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: userInput.value,
  })

  isLoading.value = true
  const question = userInput.value
  userInput.value = ''
  await scrollToBottom()

  try {
    // 创建 SSE 连接
    const eventSource = new EventSource(
      `${env.API_DOMAIN}/api/generateStream?message=${encodeURIComponent(question)}`,
    )
    let assistantMessage = ''

    eventSource.onmessage = (event) => {
      // debugger
      console.log(event)
      // const data = JSON.parse(event.data)
      // console.log(data)
      assistantMessage += event.data

      // 更新或添加助手消息
      const lastMessage = messages.value[messages.value.length - 1]
      if (lastMessage?.role === 'assistant') {
        lastMessage.content = assistantMessage
      } else {
        messages.value.push({
          role: 'assistant',
          content: assistantMessage,
        })
      }
      scrollToBottom()
    }

    eventSource.onerror = () => {
      eventSource.close()
      isLoading.value = false
    }
  } catch (error) {
    console.error('Error:', error)
    isLoading.value = false
  }
}

// 组件挂载时滚动到底部
onMounted(() => {
  scrollToBottom()
})
</script>

<style scoped>
/* 新增页面容器样式 */
.page-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f0f2f5;
  padding: 20px;
}

.chat-container {
  width: 100%;
  height: 100vh;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f5f5;
  border-radius: 8px;
  margin-bottom: 20px;
}

.message {
  margin: 12px 0;
  padding: 12px 16px;
  border-radius: 8px;
  max-width: 80%;
  white-space: pre-wrap;
}

.user {
  background: #007aff;
  color: white;
  margin-left: auto;
}

.assistant {
  background: white;
  color: #333;
  margin-right: auto;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.input-area {
  padding: 10px 0;
}

.input-area form {
  display: flex;
  gap: 10px;
}

.input-area input {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  outline: none;
}

.input-area input:focus {
  border-color: #007aff;
  box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.1);
}

.input-area button {
  padding: 12px 24px;
  background: #007aff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.2s;
}

.input-area button:hover {
  background: #0056b3;
}

.input-area button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 添加滚动条样式 */
.message-list::-webkit-scrollbar {
  width: 8px;
}

.message-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.message-list::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

.message-list::-webkit-scrollbar-thumb:hover {
  background: #555;
}

/* 添加 Markdown 相关样式 */
:deep(.message-content) {
  line-height: 1.6;
}

:deep(.message-content p) {
  margin: 8px 0;
}

:deep(.message-content pre) {
  background: #f6f8fa;
  border-radius: 6px;
  padding: 16px;
  overflow-x: auto;
  margin: 8px 0;
}

:deep(.message-content code) {
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
  font-size: 0.9em;
}

:deep(.message-content p code) {
  background: #f6f8fa;
  padding: 2px 6px;
  border-radius: 4px;
  color: #24292f;
}

:deep(.message-content blockquote) {
  border-left: 4px solid #ddd;
  margin: 8px 0;
  padding-left: 16px;
  color: #666;
}

:deep(.message-content ul),
:deep(.message-content ol) {
  padding-left: 24px;
  margin: 8px 0;
}

:deep(.message-content table) {
  border-collapse: collapse;
  width: 100%;
  margin: 8px 0;
}

:deep(.message-content th),
:deep(.message-content td) {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

:deep(.message-content th) {
  background: #f6f8fa;
}

/* 调整助手消息中代码块的样式 */
.assistant :deep(pre) {
  background: #2d2d2d;
  color: #ccc;
}

.assistant :deep(code) {
  color: inherit;
}

/* 调整用户消息中的 markdown 样式 */
.user :deep(*) {
  color: white;
}

.user :deep(pre),
.user :deep(code) {
  background: rgba(255, 255, 255, 0.1);
}

.user :deep(blockquote) {
  border-left-color: rgba(255, 255, 255, 0.3);
}
</style>
